import type { uniappRequestAdapter } from '@alova/adapter-uniapp'
import type { IResponse } from './types'
import AdapterUniapp from '@alova/adapter-uniapp'
import { createAlova } from 'alova'
import { createServerTokenAuthentication } from 'alova/client'
import VueHook from 'alova/vue'
import { toast } from '@/utils/toast'
import { ContentTypeEnum, ResultEnum, ShowMessage } from './enum'
import { useUserStore } from '@/store'
import { currRoute } from '@/utils'

// 配置动态Tag
export const API_DOMAINS = {
  DEFAULT: import.meta.env.VITE_SERVER_BASEURL,
  SECONDARY: import.meta.env.VITE_API_SECONDARY_URL,
}

/**
 * 创建请求实例
 */
const { onAuthRequired, onResponseRefreshToken } = createServerTokenAuthentication<
  typeof VueHook,
  typeof uniappRequestAdapter
>({
  refreshTokenOnError: {
    isExpired: (error) => {
      return error.response?.status === ResultEnum.Unauthorized
    },
    handler: async () => {
      try {
        // await authLogin();
      }
      catch (error) {
        // 切换到首页
        await uni.reLaunch({ url: '/pages/index/index' })
        throw error
      }
    },
  },
})

/**
 * alova 请求实例
 */
const alovaInstance = createAlova({
  baseURL: import.meta.env.VITE_API_BASE_URL,
  ...AdapterUniapp(),
  timeout: 8000,
  statesHook: VueHook,

  beforeRequest: onAuthRequired((method) => {
    // 设置默认 Content-Type
    method.config.headers = {
      ContentType: ContentTypeEnum.JSON,
      Accept: 'application/json, text/plain, */*',
      ...method.config.headers,
    }

    const { config } = method
    // const ignoreAuth = !config.meta?.ignoreAuth
    // console.log('ignoreAuth===>', ignoreAuth)
    // // 处理认证信息   自行处理认证问题
    // if (ignoreAuth) {
    //   const token = uni.getStorageSync('token')

    //   if (!token) {
    //     throw new Error('[请求错误]：未登录')
    //   }
    //   method.config.headers['ba-user-token'] = token;
    // }
	const token = uni.getStorageSync('token')
	
	if (token) {
	  method.config.headers['ba-user-token'] = token;
	}

    // 处理动态域名
    if (config.meta?.domain) {
      method.baseURL = config.meta.domain
      console.log('当前域名', method.baseURL)
    }
  }),
  
	responded: {
		onSuccess: (response, method) => {
			const { config } = method
			const { requestType } = config
			const {
			  statusCode,
			  data: rawData,
			  errMsg,
			} = response as UniNamespace.RequestSuccessCallbackResult

			// 处理特殊请求类型（上传/下载）
			if (requestType === 'upload' || requestType === 'download') {
			  return response
			}

			// 处理 HTTP 状态码错误
			if (statusCode !== 200) {
			  const errorMessage = ShowMessage(statusCode) || `HTTP请求错误[${statusCode}]`
			  console.error('errorMessage===>', errorMessage)
			  toast.info(errorMessage)
			  throw new Error(`${errorMessage}：${errMsg}`)
			}

			// 处理业务逻辑错误
			const { code, msg, data } = rawData as IResponse

			if (code !== ResultEnum.Success) {
			  if (config.meta?.toast !== false) {
				toast.info(msg)
			  }
			  // 未登录或者登录过期，清空登录信息
			  if (code === ResultEnum.NeedLogin || code === ResultEnum.LoginExpired) {
				const userStore = useUserStore()
				userStore.logout()
				const page = currRoute()
				if (['/pages-sub/order/info', '/pages-sub/order/summary'].includes((page.path))) {
					toast.info('登录过期，跳转到我的页面进行登录')
					// 跳转到我的页面
					setTimeout(() => uni.reLaunch({ url: '/pages/me/me' }), 2000)
				}
			  }
			  return {
				  data,
				  code
			  }
			  // throw new Error(`错误信息: ${msg}`, data)
			}
			// 处理成功响应，返回业务数据
			return data
		},
		onError: (error: any) => {
			return error
		}
	}

  // responded: onResponseRefreshToken((response, method) => {
  //   const { config } = method
  //   const { requestType } = config
  //   const {
  //     statusCode,
  //     data: rawData,
  //     errMsg,
  //   } = response as UniNamespace.RequestSuccessCallbackResult

  //   // 处理特殊请求类型（上传/下载）
  //   if (requestType === 'upload' || requestType === 'download') {
  //     return response
  //   }

  //   // 处理 HTTP 状态码错误
  //   if (statusCode !== 200) {
  //     const errorMessage = ShowMessage(statusCode) || `HTTP请求错误[${statusCode}]`
  //     console.error('errorMessage===>', errorMessage)
  //     toast.info(errorMessage)
  //     throw new Error(`${errorMessage}：${errMsg}`)
  //   }

  //   // 处理业务逻辑错误
  //   const { code, msg, data } = rawData as IResponse

  //   if (code !== ResultEnum.Success) {
  //     if (config.meta?.toast !== false) {
		// toast.info(msg)
  //     }
	 //  // 未登录或者登录过期，清空登录信息
	 //  if (code === ResultEnum.NeedLogin || code === ResultEnum.LoginExpired) {
	 //  	const userStore = useUserStore()
		// userStore.logout()
		// // 跳转到首页
		// setTimeout(() => uni.reLaunch({ url: '/pages/index/index' }), 1500)
	 //  }
  //     throw new Error(`请求错误[${code}]：${msg}`)
  //   }
  //   // 处理成功响应，返回业务数据
  //   return data
  // }),

})

export const http = alovaInstance
